<template>
  <div class="buildingContainer">
    <!-- 返回按钮 -->
    <button class="return" @click="returnBack">
      <img src="@/assets/pic2/转到.png" title="返回" />
    </button>
    <!-- 信息标题 -->
    <div class="buildingTitle">
      <p>
        {{ buildingDataShow ? "楼栋相关信息" : "变压器信息" }}
        <img
          src="@/assets/pic2/切换.png"
          v-show="otherData.length != 0"
          @click="buildingDataShow = !buildingDataShow"
        />
      </p>
    </div>
    <!-- 楼栋其他数据 -->
    <div class="otherData" v-show="buildingDataShow">
      <div v-for="data in otherData" :key="data">
        <span class="key"> {{ data.key }} </span>
        <span>：</span>
        <span class="value">{{ data.value }}</span>
        <span class="unit">{{ data.unit }}</span>
      </div>
    </div>
    <!--变压器数据 -->
    <div class="transformerData" v-show="!buildingDataShow">
      <div v-for="data in transformerData" :key="data">
        <span class="key"> {{ data.key }} </span>
        <!-- <span>：</span> -->
        <span class="value">{{ data.value }}</span>
        <span class="unit">{{ data.unit }}</span>
      </div>
    </div>
    <!-- 新增推荐按钮 -->
    <div
      class="addTransformerButton"
      @click="addPageShow"
      v-show="addButtonShow"
    >
      <img src="@/assets/pic2/新增.png" />
      台区负荷容量推演
    </div>
  </div>
</template>

<script>
/*eslint-disable */
import axios from "axios";
import pubsub from "pubsub-js";
import url from "@/components/URL.json";
import { getCurrentInstance, onActivated, onMounted } from "vue-demi";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";

import supplyRange from "@/json/供电范围1226.json";

export default {
  name: "buildingSelected",
  data() {
    return {
      addButtonShow: false,
      ptShow: true,
      fwbm: "",
      code: 0,
      jzmj: 0,
      otherData: [],
      transformerData: [],
      buildingDataShow: false,
      photoShow: true,
      title: "人员信息库",
      imgPath: "暂无图片",
      downloadFileName: "",
      peopleData: [],
      location_x: "",
      location_y: "",
      rewriteShow: true,
      building: {},
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    let subList = [];
    let buidlingData = {};
    let unitList = ["", "层", "m²", "层", "间", "间", "人", "", "", "", ""];
    let keyList = [
      "楼栋地址",
      "总层数",
      "占地面积",
      "出租层数",
      "住宅类出租间数",
      "商铺间数",
      "居住人数",
      "屋主是否在同栋楼",
      "是否安装智能门禁",
      "网格",
      "网格员",
    ];
    let riskParams = {};

    onMounted(() => {
      riskParams = {};

      // 接收pubsub
      subscribeList();
    });

    // 接收pubsub信息
    function subscribeList() {
      subList[0] = pubsub.subscribe("buildingSelect", (n, data) => {
        proxy.otherData = [];
        console.log(data);
        store.commit("tempStorageB", data);
        proxy.building = data;
        // 容量推演功能显隐控制
        let num = Number(
          data.attributes["BYQMC"].split("村")[1].split("号")[0]
        );
        console.log(num);
        if (num === 12 || num === 13 || num === 14) {
          proxy.addButtonShow = true;
        } else {
          proxy.addButtonShow = false;
        }
        // 楼栋信息
        getBuilidngData(data);
      });
      // 楼栋人口/周边显示控制
      subList[1] = pubsub.subscribe("optionRenew", (n, data) => {
        // 展示照片
        proxy.photoShow = data === "人口信息";
        // 标题更改
        proxy.title = data === "人口信息" ? "人员信息库" : "楼栋照片";
        // 添加或删除POI点
        if (data != "人口信息") {
          // 传输缓冲区中心坐标
          pubsub.publish("bufferCenter", {
            x: buidlingData.attributes["X"],
            y: buidlingData.attributes["Y"],
          });
        } else {
          pubsub.publish("quitBuffer");
        }
      });
      // 人口数据重载
      subList[2] = pubsub.subscribe("reSearchPeople", (n, data) => {
        getPeopleByBuilding(proxy.building);
      });
      // 变压器信息接收
      subList[3] = pubsub.subscribe("transformerData", (n, data) => {
        pubsub.publish("peopletTablesShow", false);
        proxy.ptShow = false;
        proxy.rewriteShow = false;
        pubsub.publish("RentDataShow", false);
        // console.log(data);
        // 数据栏显示
        proxy.buildingDataShow = false;
        let keyList = [
          "PBID",
          "BYQMC",
          "SSKC",
          "RL_kVA",
          "F2023_ZDFZL",
          "SFWCND",
          "DYYH",
          "GDBJ",
          "SFYP2_0TQ",
          "DYLL",
          "mj",
        ];
        let valueList = [
          "配电ID",
          "名称",
          "所属馈线",
          "容量",
          "23年最大负载",
          "是否完成拿地",
          "低压用户",
          "供电半径",
          "是否营配2.0台区",
          "低压联络",
          "供电范围面积",
        ];
        let unitList = ["", "", "", "kVA", "%", "", "", "m", "", "", "m²"];
        let arr = [];
        for (let i = 0; i < keyList.length; i++) {
          for (let key in data.attributes) {
            if (key === keyList[i]) {
              if (key === "F2023_ZDFZL") {
                arr.push({
                  key: " " + valueList[i] + ":",
                  value: (data.attributes[key] * 100).toFixed(2),
                  unit: unitList[i],
                });
              } else {
                arr.push({
                  key: " " + valueList[i] + ":",
                  value: data.attributes[key],
                  unit: unitList[i],
                });
              }
            }
          }
        }
        proxy.transformerData = arr;
        // 显示供电范围
        supplyRange.features.forEach((range) => {
          if (range.attributes["PBID"] === data.attributes["PBID"]) {
            pubsub.publish("supplyRangeShow", range);
          }
        });
      });
      // 风险参数接收
      subList[4] = pubsub.subscribe("riskParams", (n, data) => {
        riskParams = data;
      });
    }

    // 建筑信息填入
    function getBuilidngData(building) {
      console.log(building);
      // 楼栋坐标字符串
      let x =
        Number(building.attributes["x"].toString().split(".")[1].substr(0, 4)) /
          10000 +
        Number(building.attributes["x"].toString().split(".")[0]);
      let y =
        Number(building.attributes["y"].toString().split(".")[1].substr(0, 4)) /
          10000 +
        Number(building.attributes["y"].toString().split(".")[0]);
      axios({
        method: "get",
        url: url.basicURL + "getBuilding",
        params: { x: x, y: y },
      }).then((res) => {
        // console.log(res.data.length);
        if (res.data.length != 0) {
          // console.log("###");
          proxy.buildingDataShow = true;
          buidlingData = res.data[0];
          let arr = [];
          let i = 0;
          // console.log(buidlingData);
          keyList.forEach((key) => {
            if (key === "楼栋地址") {
              let building =
                buidlingData[key].split("大同村")[1] != undefined
                  ? buidlingData[key].split("大同村")[1]
                  : buidlingData[key].split("东涌镇")[1];
              arr.push({
                key: " " + key + " ",
                value: building,
                unit: unitList[i],
              });
            } else if (key === "占地面积") {
              arr.push({
                key: " " + key + " ",
                value: 25.43,
                unit: unitList[i],
              });
            } else {
              arr.push({
                key: " " + key + " ",
                value: buidlingData[key],
                unit: unitList[i],
              });
            }
            i++;
          });
          console.log("楼栋信息:", arr);
          proxy.otherData = arr;
        }
      });
    }

    // 查询下属人口信息
    function getPeopleByBuilding(building) {
      // 读取XY,截取小数点前四位
      let x =
        Number(building.attributes["x"].toString().split(".")[1].substr(0, 5)) /
          100000 +
        Number(building.attributes["x"].toString().split(".")[0]);
      let y =
        Number(building.attributes["y"].toString().split(".")[1].substr(0, 5)) /
          100000 +
        Number(building.attributes["y"].toString().split(".")[0]);
      proxy.location_x = x;
      proxy.location_y = y;
      //   发送至后端查询数据库
      axios({
        method: "get",
        url: url.basicURL + "getPeopleByBuilding",
        params: {
          location_x: x,
          location_y: y,
        },
      }).then((res) => {
        console.log("人口信息:", res.data);
        //判断是否有数据
        if (res.data.length != 0) {
          console.log(res.data);
          // 开启显示
          proxy.ptShow = true;
          pubsub.publish("peopletTablesShow", true);
          // 填入人口信息
          peopleDataInput(res.data);
          // 人口信息导出预备
          proxy.peopleData = res.data;
          proxy.downloadFileName = res.data[0]["地址"].split("东涌镇大同村")[1];
        } else {
          proxy.rewriteShow = false;
          // ElMessage({
          //   message: "暂无人口数据",
          //   type: "error",
          //   offset: 50,
          //   duration: 4000,
          // });
          // 开启显示
          proxy.ptShow = false;
          pubsub.publish("peopletTablesShow", false);
        }
      });
    }

    // 人口信息填入表格
    function peopleDataInput(peopleList) {
      pubsub.publish("peopleInBuilding", peopleList);
      // 更新人口表
      pubsub.publish("peopleDataInpt", peopleList);
    }

    //查询出租关系信息
    function getRentData(building) {
      // 楼栋坐标字符串
      let x =
        Number(building.attributes["x"].toString().split(".")[1].substr(0, 4)) /
          10000 +
        Number(building.attributes["x"].toString().split(".")[0]);
      let y =
        Number(building.attributes["y"].toString().split(".")[1].substr(0, 4)) /
          10000 +
        Number(building.attributes["y"].toString().split(".")[0]);
      // 查询数据库
      axios({
        method: "get",
        url: url.basicURL + "getRent",
        params: { x: x, y: y },
      }).then((res) => {
        console.log("出租关系:", res.data);
        // 判断是否有数据
        if (res.data.length != 0) {
          pubsub.publish("RentDataShow", true);
          // 更新出租关系
          pubsub.publish("RentDataInput", res.data);
        } else {
          // ElMessage({
          //   message: "暂无出租关系数据",
          //   type: "error",
          //   offset: 50,
          //   duration: 4000,
          // });
          pubsub.publish("RentDataShow", false);
        }
      });
    }

    // 返回
    function returnBack() {
      pubsub.publish("returnFromBuilding", "@");
      pubsub.publish("needReturn", "@");
      pubsub.publish("hierarchyQuit", "@");
      pubsub.publish("GFshowChange", true);
      pubsub.publish("wakeUpShowChange", true);
      // 来自点选
      if (store.state.fromClick) {
        pubsub.publish("needCut", true);
        pubsub.publish("FirstPageShow", "@");
        router.push({
          path: "/main",
        });
        pubsub.publish("cameraRotation", "off");
      }
      // 来自人口
      else if (store.state.fromPeople) {
        store.commit("isFromPeople", false);
        router.push({
          path: "/peopleSelected",
        });
      }
      // 来自网格
      else if (store.state.fromNet) {
        store.commit("isFromNet", false);
        router.push({
          path: "/netCut",
        });
        pubsub.publish("firstPageShowChange", false);
        pubsub.publish("cutByNet", store.state.polygon.attributes.name);
        setTimeout(() => {
          pubsub.publish("polygon", store.state.polygon);
        }, 300);
      }
      // 来自风险监测
      else if (Object.entries(riskParams).length != 0) {
        router.push({
          path: "/riskWarning",
          query: riskParams,
        });
      }
      // 来自主页
      else {
        // pubsub.publish("FirstPageShow", "@");
        // pubsub.publish("optionRenew", "人口信息");
        // window.history.go(-1);
        // pubsub.publish("cameraRotation", "off");
        router.push({
          path: "/",
        });
      }
    }

    // 配变位置推荐跳转
    function addPageShow() {
      router.push({
        path: "/loadCapacity",
        query: {
          id: proxy.building.attributes["PBID"],
          name: proxy.building.attributes["BYQMC"],
        },
      });
    }

    return { returnBack, subList, store, router, addPageShow };
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
  beforeRouteLeave(to) {
    // console.log("订阅清理");
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
    this.store.commit("isFromClick", false);
  },
};
</script>

<style lang="less" scoped>
.addTransformerButton {
  position: relative;
  top: 39%;
  // margin: 5%;
  margin-left: 1%;
  display: block;
  background-color: #f4ea2a;
  padding: 2%;
  width: 50%;
  border-radius: 7px;
  font-size: 150%;
  font-weight: bold;
  text-align: center;
  > img {
    width: 10%;
    margin-bottom: 2%;
  }
}

.addTransformerButton:hover {
  cursor: pointer;
}

.return {
  background-color: #1296db;
  width: 40px;
  height: 40px;
  position: absolute;
  z-index: 1000;
  top: 2%;
  right: 2%;
  outline: none;
  border: none;
  border-radius: 50%;
  > img {
  }
}

.buildingContainer {
  //   border: 1px red solid;
  height: 100%;
  overflow: hidden;
}
.buildingIcon {
  top: 3%;
  right: -70%;
  width: 30%;
  position: relative;
  > .imgContainer {
    background-color: rgba(0, 0, 0, 0.3);
    box-shadow: 0px 0px 10px 2px #1296db;
    border-radius: 50%;
    width: 100px;
    height: 100px;
    position: relative;
    left: 12%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    > img {
      width: 80%;
      margin-bottom: 10%;
    }
  }
}
.buildingTitle,
.peopleTitle {
  height: 5%;
  > p {
    width: 60%;
    background-image: ~"url(@{app-images-root}/topmenu_bg.png)";
    background-size: 100% 100%;
    font-size: 170%;
    font-weight: bold;
    text-align: center;
    padding: 3% 0%;
    color: white;
    margin-left: -10%;
  }
}

.peopleTitle {
  > p {
    background-image: ~"url(@{app-images-root}/topmenu_bg_select.png)";
  }
}

.buildingTitle {
  margin-top: 4%;
  margin-left: 4%;
  > p > img {
    display: inline-block;
    width: 25px;
    margin-bottom: 5px;
  }
}
.peopleTitle {
  margin-top: 3%;
}

.otherData {
  position: relative;
  top: 1%;
  height: 50%;

  > div {
    height: 10%;
    padding: 0 3.3%;
    border-bottom: 1px solid;
    border-image: linear-gradient(to right, #fff, #0000);
    border-image-slice: 1;

    > span {
      color: #1296db;
      font-size: 170%;
      font-weight: bold;
    }
    > .key {
      color: #1296db;
      font-size: 170%;
      font-weight: bold;
      // border-bottom: white 1px solid;
    }
    > .value {
      font-family: "Agency FB";
      font-size: 250%;
      color: white;
      margin-left: 0%;
      // border-bottom: gray 1px solid;
    }
    > .unit {
      color: white;
      font-size: 150%;
      margin-left: 2%;
      // border-bottom: gray 1px solid;
    }
  }
}

.transformerData {
  position: relative;
  top: 1%;
  max-height: 50%;

  > div {
    padding: 0.2% 2%;
    // border-bottom: white 1px solid;
    border-bottom: 1px solid;
    border-image: linear-gradient(to right, #fff, #0000);
    border-image-slice: 1;

    > span {
      color: white;
      // text-align: center;
      font-size: 170%;
      font-weight: bold;
      display: inline-block;
    }
    > .key {
      display: block;
      width: 50%;
      // background-color: #1296db;
      // color: white;
      color: #1296db;
      font-size: 170%;
      font-weight: bold;
      // border-radius: 5px;
      padding: 1% 0%;
    }
    > .value {
      font-family: "Agency FB";
      font-size: 250%;
      color: white;
      margin-left: 0%;
      // border-bottom: gray 1px solid;
    }
    > .unit {
      color: white;
      font-size: 150%;
      margin-left: 2%;
      // border-bottom: gray 1px solid;
    }
  }
}
</style>